package Sort_Work;

import java.util.Arrays;

/**
 * 归并排序
 * 时间复杂度：O(N*logN)
 * 空间复杂度：O(N)
 * 稳定性：稳定
 * （归并 插入 冒泡 是稳定的）
 */
public class Merge_Sort {
    //先分解 再合并 合并时申请一块空间 排好序后拷贝回原数组
    public static void mergeSort(int[] array) {
        margeFunc(array,0, array.length-1);
    }
    //分割
    public static void margeFunc(int[] array,int left,int right) {
        if(left >= right) {
            return;
        }
        //分割找到中间节点
        int mid = left + ((right-left)>>1);
        margeFunc(array,left,mid);
        margeFunc(array,mid+1,right);
        marge(array,left,mid,right);
    }
    //合并
    public static void marge(int[] array,int left,int mid,int right) {
        int s1 = left;
        int e1 = mid;
        int s2 = mid+1;
        int e2 = right;
        int k = 0;
        int[] tmpArray = new int[right-left+1];

        while (s1 <= e1 && s2 <= e2) {
            if(array[s1] < array[s2]) {
                tmpArray[k++] = array[s1++];
            } else {
                tmpArray[k++] = array[s2++];
            }
        }
        if(s1 <= e1) {
            while (s1 <= e1) {
                tmpArray[k++] = array[s1++];
            }
        }
        if(s2 <= e2) {
            while (s2 <= e2) {
                tmpArray[k++] = array[s2++];
            }
        }

        for (int i = 0; i < k; i++) {
            array[left+i] = tmpArray[i];
        }
    }
    ////////////////////////////////////////////////////
    //非递归实现
    //重点在于合并怎么写
    public static void mergeSortNor(int[] array) {
        int gap = 1;
        //最外层控制组数
        while (gap < array.length) {
            //每一组进行排序
            for (int i = 0; i < array.length; i=i+2*gap) {
                int left = i;
                int mid = left + gap - 1;
                if (mid >= array.length) {
                    mid = array.length - 1;
                }
                int right = mid + gap;
                if (right >= array.length) {
                    right = array.length - 1;
                }
                marge(array,left,mid,right);
            }
            gap *= 2;
        }
    }

    public static void main(String[] args) {
        int[] array = {1,3,5,7,9,2,4,6,8};
        mergeSort(array);
        System.out.println(Arrays.toString(array));
    }
}
